package com.cherry.androidcode.onresult

import android.content.Intent
import android.os.Bundle
import android.util.SparseArray
import androidx.fragment.app.Fragment
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject

/**
 * @author 董棉生(dongmiansheng@parkingwang.com)
 * @since 18-9-27
 */

class AvoidOnResultFragment : Fragment() {
    private val subjects by lazy {
        SparseArray<PublishSubject<ActivityResultInfo>>()
    }
    private val callbacks by lazy {
        SparseArray<AvoidOnResult.Callback>()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        retainInstance = true
    }

    fun startForResult(intent: Intent): Observable<ActivityResultInfo> {
        val subject = PublishSubject.create<ActivityResultInfo>()
        return subject.doOnSubscribe {
            val requestCode = shortHashCode(subject.hashCode())
            subjects.put(requestCode, subject)
            startActivityForResult(intent, requestCode)
        }
    }

    fun startForResult(intent: Intent, callback: AvoidOnResult.Callback) {
        val requestCode = shortHashCode(callback.hashCode())
        callbacks.put(requestCode, callback)
        startActivityForResult(intent, requestCode)
    }

    private fun shortHashCode(callback: Any) = callback.hashCode() and 0x0000ffff

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //rxjava方式的处理
        subjects[requestCode]?.let {
            it.onNext(ActivityResultInfo(resultCode, data))
            it.onComplete()
        }
        subjects.remove(requestCode)

        //callback方式的处理
        callbacks[requestCode]?.onActivityResult(resultCode, data)
        callbacks.remove(requestCode)
    }

}